package com.itheima.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CheckGroupService;
import com.itheima.service.SetmealService;
import com.itheima.utils.QinniuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    SetmealService setmealService;
    @Autowired
    JedisPool jedisPool;
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        try {
            //修改图片名称(1.jpg,1.jpeg)后缀名不能改
            String originalFilename = imgFile.getOriginalFilename();
            int index = originalFilename.lastIndexOf(".");
            String suffix = originalFilename.substring(index);
            String newFileName=UUID.randomUUID().toString()+suffix;
            //调用图片上传工具
            QinniuUtil.upload(imgFile.getBytes(),newFileName);
            //把所有上传成功的图片放在第一个集合
jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFileName);//链接需要关闭
            //返回图片名称
            return Result.success("",newFileName);
            //一定返回新文件名称
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }


        //调用图片上传工具
        //返回图片名称(用于回显)
    }
    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal){
        setmealService.add(setmeal);
        //把保存的到数据库里面的图片保存到第二个集合
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());//链接需要关闭

        return Result.success("");

    }
    @RequestMapping("/findPage")
    public PageResult findPageBean(@RequestBody QueryPageBean queryPageBean){
        return  setmealService.findPage(queryPageBean);
    }
}
